package com.crm.controller.invoiceController;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.crm.beans.SupplyParts;
import com.crm.dao.OpportunityDAO;
import com.crm.dao.PODAO;
import com.crm.dao.PartsDAO;
import com.crm.dao.QuotationDAO;
import com.crm.dao.SupplierDAO;
import com.crm.dao.SupplierInvoiceDAO;
import com.crm.dao.SupplyOrderDAO;
import com.crm.entity.Business;
import com.crm.entity.Clientdet;
import com.crm.entity.Opportunity;
import com.crm.entity.PO;
import com.crm.entity.Parts;
import com.crm.entity.Quotation;
import com.crm.entity.Supplier;
import com.crm.entity.SupplierInvoice;
import com.crm.entity.SupplyOrder;
import com.crm.util.Constants;


@Controller
@RequestMapping("/suppInvoice")
public class SupplierInvoiceController {
	protected final Log logger = LogFactory.getLog(getClass());
	//OpportunityDAO opportunityDAO=new OpportunityDAO();
	SupplierInvoiceDAO supplierInvoiceDAO=new SupplierInvoiceDAO();
	QuotationDAO quotationDAO=new QuotationDAO();
	
	SupplierDAO supplierDAO=new SupplierDAO();
	PODAO poDAO=new PODAO();
	PartsDAO partsDAO=new PartsDAO();
	
@RequestMapping( "/show.do") 
public ModelAndView show(HttpServletRequest request,HttpSession session, ModelAndView model) throws Exception{
				Business bus=(Business)session.getAttribute("business");
				if(bus==null)return new ModelAndView("/jsp/index.jsp");
				int busid=bus.getBusinessId();
				logger.info("Business Name Is:"+bus.getBusinessName());
				
				String status=Constants.ST_GEN_PO;
				List<Opportunity> opr=OpportunityDAO.getSingleInstance().getByStatus(status, busid);
				logger.info("opportunity list is "+opr);
				return model = new ModelAndView("/jsp/supplierInvoice.jsp")
				.addObject("submenu","invoice")
				.addObject("menuName","invoice")		
				.addObject("opprtunity",opr);
	}
@RequestMapping( "/printsupcopy.do") 
public ModelAndView printpi(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
	Business bus=(Business)session.getAttribute("business");
	if(bus==null)return new ModelAndView("/jsp/index.jsp");
		
		List<SupplierInvoice> supplist=null;
		try{supplist=supplierInvoiceDAO.getAllSuppCopys(bus.getBusinessId());
				logger.info("attachment list is "+supplist);
		}catch(NullPointerException e){
			e.printStackTrace();
		}
		  model = new ModelAndView("/jsp/printSupplierCopy.jsp");
			model.addObject("supplist",supplist);
			model.addObject("submenu", "invoice");
			model.addObject("menuName","invoice");
			 
	 
			return model;
}
@RequestMapping( "/printsearch.do") 
public List<SupplierInvoice> printserach(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
	Business bus=(Business)session.getAttribute("business");
	String scopyno = req.getParameter("scopyno");
		List<SupplierInvoice> supplist=null;
		try{supplist=supplierInvoiceDAO.getAllSuppByNo(scopyno,bus.getBusinessId());
				logger.info("attachment list is "+supplist);
		}catch(NullPointerException e){
			e.printStackTrace();
		}
		 
			return supplist;
		
			 
}


@RequestMapping(value = "/get_supcopy.do", method = RequestMethod.GET)
public String pinting(HttpSession session, HttpServletRequest request,
		HttpServletResponse response) throws Exception {
	Business bus = (Business) session.getAttribute("business");

	String idno = request.getParameter("quotid");
	int id=Integer.parseInt(idno);
	SupplierInvoice supinvoice = supplierInvoiceDAO.getsupInvoiceById(id);
	logger.info("the business id is  " + bus.getBusinessId());
	byte[] pdfReport = supinvoice.getSuppliercopy();
	logger.info("the length of pdf is" + pdfReport.length);
	logger.info("the length of pdf is" + pdfReport.toString());
	ServletOutputStream servletOutputStream = response.getOutputStream();
	String fileName = "quotation.doc";
	response.setHeader("Content-Disposition", "inline; filename=" + fileName);
	 response.setContentType("txt/image");
	response.setContentLength(pdfReport.length);
	servletOutputStream.write(pdfReport);
	servletOutputStream.flush();
	servletOutputStream.close();
	return null;

}
@RequestMapping("/getSupplyOrderNo.do")
public @ResponseBody String getSupplyOrderNo(HttpSession session,HttpServletRequest request,HttpServletResponse response){
	Business bus=(Business)session.getAttribute("business");
	int busid=bus.getBusinessId();
	String refno=request.getParameter("refno");
	
	
	
	Opportunity o = new Opportunity();
	try {
		o = OpportunityDAO.getSingleInstance().getByRefNo(busid, refno);
	} catch (Exception e) {
		e.printStackTrace();
	}
	Quotation q=new Quotation();
	try {
		q=quotationDAO.getRecentQuotNumByEnq(busid, o.getId());
	} catch (Exception e) {
		e.printStackTrace();
	}
	int quotid=q.getId();
	SupplyOrderDAO sodao=new SupplyOrderDAO();
	List<SupplyOrder> lso=new ArrayList<SupplyOrder>();
	try {
		lso=sodao.getByQuotid(busid,quotid);
	} catch (Exception e) {
		e.printStackTrace();
	}
	SupplyOrder so=new SupplyOrder();
	for(SupplyOrder s:lso){
		so=s;
	}
	return so.getSuplyOrderNum()+","+so.getDate();
}
@RequestMapping( "/getInvoice.do") 
public ModelAndView getInvoice(HttpServletRequest request,HttpSession session, ModelAndView model) throws Exception{
	Business bus=(Business)session.getAttribute("business");
	if(bus==null)return new ModelAndView("/jsp/index.jsp");
	int busid=bus.getBusinessId();
	
	
	String refno=request.getParameter("refno");
	String supplier=request.getParameter("supplier");
	System.out.println("Supplier Name In Controller Is:"+supplier);
	Opportunity o=OpportunityDAO.getSingleInstance().getByRefNo(busid, refno);
	int enqid=o.getId();
	
	Supplier ls = new Supplier();
	try {
		ls = supplierDAO.getSupplier(supplier, busid);
	} catch (Exception e2) {
		e2.printStackTrace();
	}
	int suid=ls.getId();
	List<PO> lpo=new ArrayList<PO>();
	try {
		lpo=poDAO.getPurchaseOrder(enqid, suid, busid);
	} catch (Exception e1) {
		e1.printStackTrace();
	}
	System.out.println("the listpart is"+lpo);
	List<SupplyParts> lsParts=new ArrayList<SupplyParts>();
	PartsDAO partsdao=new PartsDAO();
	Iterator<PO> its=lpo.iterator();
	while(its.hasNext()){
		Object obj=its.next();
		PO p=(PO)obj;
		Parts pt = null;
		try {
			pt = partsDAO.findByPartIdEnqId(enqid,p.getPartId(), busid);
			System.out.println("the part obj is"+pt);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		partsdao.getPrtId(o.getRefNum(),pt.getPrtnum(),pt.getDescription(),enqid,busid);
		
		System.out.println("the part name is"+pt.getPrtnum()+"pat id is"+pt.getPartid());
		SupplyParts supPart=new SupplyParts(pt.getDescription(),pt.getMake(),pt.getPrtnum(),p.getQty()+"",p.getUnitPrice()+"",p.getTotalPrice()+"");
		supPart.setPartId(p.getPartId());
		
		lsParts.add(supPart);
	}
	
	
	return model = new ModelAndView("/jsp/supplierInvoiceRes.jsp")
	.addObject("submenu","invoice")
	.addObject("supplyParts",lsParts)
	.addObject("menuName","invoice");
}
@RequestMapping( "/getSupplier.do") 
public @ResponseBody String getSuppliers(HttpServletRequest request,HttpSession session) throws Exception{
	Business bus=(Business)session.getAttribute("business");
	int busid=bus.getBusinessId();
	logger.info("Business Name Is:"+bus.getBusinessName());
	
	String refnum=request.getParameter("refno").toString();
	System.out.println("Ref NO In Aupplier Invoice Controller Is:"+refnum);
	Opportunity o=OpportunityDAO.getSingleInstance().getByRefNo(busid,refnum);
	Clientdet clientdet=null;
	clientdet=o.getClientId();
	clientdet.setDivision(o.getDivision());
	int enqid=0;
	if(o!=null) enqid=o.getId();
	List<Integer> ls = new ArrayList<Integer>();
	try {
		ls = poDAO.getSupp(enqid,busid);
	} catch (Exception e1) {
		e1.printStackTrace();
	}
	System.out.println("the supplier list is"+ls);
	  StringBuilder sb = new StringBuilder();
	Iterator<Integer> it=ls.iterator();
	while(it.hasNext()){
		int supid=it.next();
		Supplier s = null;
		try {
			s = supplierDAO.findById(supid,busid);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		String supName=null;
		
		if(s!=null){
			supName=s.getName();
		}
			sb.append(","+supName);
		
	}
	sb.append("@"+o.getOrganisation()+","+o.getDivision()+","+o.getUser());
	System.out.println("the sb is"+sb);
		return sb.toString();
	}


@RequestMapping( "/saveInvoice.do") 
public ModelAndView saveInvoice(HttpServletRequest request,HttpSession session, ModelAndView model) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		int busid=bus.getBusinessId();
		
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = null;
		try{
			file=multipartRequest.getFile("suppliercopy");
			System.out.println("In Try Ending");
		}catch(NullPointerException npe){
			npe.printStackTrace();
		}
		byte[] bsupplierCopy=file.getBytes();
		System.out.println("File Bytes Is: "+bsupplierCopy);
		String ref=request.getParameter("reflist");
		Opportunity o=OpportunityDAO.getSingleInstance().getByRefNo(busid, ref);
		int enqid=o.getId();
		
		String invoiceNum=request.getParameter("invoiceNum");
		String sup = request.getParameter("supplier");
		Supplier s = supplierDAO.getByName(sup, busid);
		
		
			
			Date date=new java.sql.Date(new java.util.Date().getTime());
		
			
			SupplierInvoice si = new SupplierInvoice(bus,enqid,s.getId(),bsupplierCopy,invoiceNum,date);
			
			
			/*si.setBusinessId(bus);
			si.setEnqId(enqid);
			si.setSupplierId(s.getId());
			si.setSuppliercopy(b);
			si.setInvoiceNum(invoiceNum);
			si.setDate(date);*/
			try {
				supplierInvoiceDAO.insert(si);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		
		String status=Constants.ST_GENERATED_SUP_INVOICE;
		OpportunityDAO.getSingleInstance().updateStatus(busid, status, enqid);
		return model=new ModelAndView("/jsp/supplierInvoice.jsp")
		.addObject("submenu","invoice")
		.addObject("menuName","invoice")
		.addObject("msg","Succesfully saved Supplier Invoice");
	}
}
